import asyncio
from typing import List, Optional
import traceback
from datetime import datetime
import sys

from common.log import log
from settings.config import settings

class ShellUtil():
    
    @staticmethod
    async def start_command(command: str, work_dir: str) -> Optional[asyncio.subprocess.Process]:
        try:
            start_time = datetime.now().strftime(settings.DATETIME_FORMAT)
            log.info(f"开始执行命令：{start_time}")
            process = await asyncio.create_subprocess_shell(
                command,
                stdout=asyncio.subprocess.PIPE,
                stderr=asyncio.subprocess.PIPE,
                shell=True,
                cwd=work_dir
            )
            return process
        except Exception as e:
            log.error(f"命令 {command} 启动过程发生异常：{e}")
        return None
    
    
    @staticmethod
    async def wait_for_command(process: asyncio.subprocess.Process, command: str) -> bool:
        if not process:
            log.error("无效的进程对象")
            return False

        try:
            stdout, stderr = await process.communicate()
            end_time = datetime.now().strftime(settings.DATETIME_FORMAT)
            log.info(f"执行结束：{end_time}")

            if process.returncode == 0:
                log.info(f"命令 {command} 执行成功")
                return True
            else:
                log.error(f"命令 {command} 执行失败，退出码: {process.returncode}")
                log.error(f"stderr: {stderr.decode('utf-8')}")
                return False
        except Exception as e:
            log.error(f"命令 {command} 等待过程发生异常：{e}")
        return False